package com.smartstate.ems.quartz;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.smartstate.ems.core.ScheduleConstants;
import com.smartstate.ems.dto.EquipmentDTO;
import com.smartstate.ems.entity.*;
import com.smartstate.ems.exception.ErrorEnums;
import com.smartstate.ems.exception.MyRException;
import com.smartstate.ems.mapper.*;
import com.smartstate.ems.service.IQuartzJobService;
import com.smartstate.ems.util.QuartzUtils;
import com.smartstate.ems.entity.*;
import com.smartstate.ems.mapper.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 根据设备类型查询实时数据
 */
@Log4j2
@Component("quartz")
public class QuartzMethods {

    @Resource
    private PowerEquipmentEntityDao powerEquipmentEntityDao;

    @Resource
    private EquipmentConfigMapper equipmentConfigMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ElectricMeterMapper electricMeterMapper;

    @Autowired
    GasMapper gasMapper;

    @Autowired
    SteamMapper steamMapper;

    @Resource
    private ObjMoudelMapper objMoudelMapper;

    @Resource
    private ObjMiddleMapper objMiddleMapper;

    @Resource
    private WaterMeterMapper waterMeterMapper;

    @Autowired
    SortingMapper sortingMapper;

    @Autowired
    DehumidifierTDMapper dehumidifierMapper;

    @Autowired
    EquipmentMapper equipmentMapper;

    @Autowired
    QuartzMapper quartzMapper;

    @Autowired
    IQuartzJobService iQuartzJobService;


    @Autowired
    RedisTemplate redisTemplate;

//    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    /**
     * 存放上次的值
     * key:dataId
     * value:上次读取到的值
     */
    private HashMap<String, Float> hashMap = new HashMap<String, Float>();

    /**
     * 存放设备主键id和设备id
     * key:设备主键id
     * value:楼宇id
     */
    private HashMap<String, Float> idAndDeviceId = new HashMap<String, Float>();


    /**
     * 电表类型 ElectricMeter
     *
     * @param id
     */
    public void electricMeter(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                electricMeterMethod(id);
            }
        });
    }

    //TODO
    public void electricMeterMethod(String id) {
        try {
            Equipment equipment = equipmentMapper.selectById(id);
            //根据设备ID查询Redis中的数据
            Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
            if (entries.size() > 0) {
                //根据deviceId查询楼层id
                String idAndType = getObjId(equipment);
                //Redis中有值，就存入TD中
                //根据设备id查询tages，遍历tages中的属性，是否做差值计算
                EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
                ElectricMeter electricMeter = new ElectricMeter();
                electricMeter.setEquipment_id(equipment.getId());
                electricMeter.setDeviceId(equipment.getDeviceId());
                electricMeter.setTs(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                electricMeter.setId(IdUtil.simpleUUID());
                electricMeter.setObjId(idAndType);
                if (configuration != null && configuration.getTags() != null) {
                    List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(configuration.getTags(), EquipmentDTO.AddressData.class);
                    for (EquipmentDTO.AddressData addressData : addressDataList) {
                        //有功电能
//                        if ((addressData.getAttributeName() != null) && (addressData.getAttributeName().equals("active_energy"))) {
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("activeEnergy").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            //千瓦时转换成瓦时
//                            BigDecimal bigDecimal = new BigDecimal(parseFloat);
//                            BigDecimal divide = bigDecimal.multiply(new BigDecimal(1000));
//                            parseFloat = Float.parseFloat(divide.toString());
                            electricMeter.setActive_energy(parseFloat);
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    electricMeter.setDet_active_energy(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    electricMeter.setDet_active_energy(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }

                        //无功电能
//                        if ((addressData.getAttributeName() != null) && (addressData.getAttributeName().equals("reactive_energy"))) {
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("reactiveEnergy").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            //千瓦时转换成瓦时
//                            BigDecimal bigDecimal = new BigDecimal(parseFloat);
//                            BigDecimal divide = bigDecimal.multiply(new BigDecimal(1000));
//                            parseFloat = Float.parseFloat(divide.toString());
                            electricMeter.setReactive_energy(parseFloat);
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    electricMeter.setDet_reactive_energy(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    electricMeter.setDet_reactive_energy(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }

                        //视在能量
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("apparentEnergy").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            //千瓦时转换成瓦时
//                            BigDecimal bigDecimal = new BigDecimal(parseFloat);
//                            BigDecimal divide = bigDecimal.multiply(new BigDecimal(1000));
//                            parseFloat = Float.parseFloat(divide.toString());
                            electricMeter.setApparent_energy(parseFloat);
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    electricMeter.setDet_apparent_energy(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    electricMeter.setDet_apparent_energy(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }
                    }
                    boolean b = electricMeterMapper.addElectricMeter(electricMeter);
//                    System.out.println("电表数据存入TD是否成功........" + b);
                }
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
//            log.info("电表数据存入TD失败");
        }
    }


    /**
     * 水表类型
     *
     * @param id
     */
    public void WaterMeter(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                WaterMeterMethod(id);
            }
        });
    }

    public void WaterMeterMethod(String id) {
        try {
            Equipment equipment = equipmentMapper.selectById(id);
            Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
            if (entries.size() > 0) {
                //根据deviceId查询楼层id
                String idAndType = getObjId(equipment);
                WaterMeter waterMeter = new WaterMeter();
                waterMeter.setEquipment_id(equipment.getId());
                waterMeter.setId(IdUtil.simpleUUID());
                waterMeter.setTs(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                waterMeter.setObjId(idAndType);
                waterMeter.setDeviceId(equipment.getDeviceId());
                //根据设备id查询tags
                EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
                if (configuration != null && configuration.getTags() != null) {
                    List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(configuration.getTags(), EquipmentDTO.AddressData.class);
                    for (EquipmentDTO.AddressData addressData : addressDataList) {
                        //瞬时计量
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && ("instantaneous").equals(addressData.getAttributeName())) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            waterMeter.setInstantaneous(parseFloat);
                            //是否做差值计算
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    waterMeter.setDet_instantaneous(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    waterMeter.setDet_instantaneous(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }

                        //总量
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("total").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            waterMeter.setTotal(parseFloat);
                            //是否做差值计算
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    waterMeter.setDet_total(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    waterMeter.setDet_total(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }
                    }
                }
                boolean b = waterMeterMapper.addWaterMeter(waterMeter);
//                System.err.println("水表表数据存入TD是否成功：" + b);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
//            log.info("水表数据存入TD失败");
        }
    }

    /**
     * 天然气表方法
     *
     * @param id
     */
    public void getGas(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                GasMethod(id);
            }
        });
    }

    public void GasMethod(@RequestParam String id) {
        try {
            Equipment equipment = equipmentMapper.selectById(id);
            Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
            if (entries.size() > 0) {
                //根据deviceId查询楼层id
                String idAndType = getObjId(equipment);
                //根据设备id查询tags
                EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
                if (configuration != null && configuration.getTags() != null) {
                    Gas gas = new Gas();
                    gas.setEquipment_id(equipment.getId());
                    gas.setId(IdUtil.simpleUUID());
                    gas.setTs(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    gas.setObjId(idAndType);
                    gas.setDeviceId(equipment.getDeviceId());
                    List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(configuration.getTags(), EquipmentDTO.AddressData.class);
                    for (EquipmentDTO.AddressData addressData : addressDataList) {
                        //瞬时计量
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("instantaneous").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            gas.setInstantaneous(parseFloat);
                            //是否做差值计算
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    gas.setDet_instantaneous(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    gas.setDet_instantaneous(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }

                        //总量
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("total").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            gas.setTotal(parseFloat);
                            //是否做差值计算
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    gas.setDet_total(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    gas.setDet_total(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }
                    }
                    boolean b = gasMapper.addGas(gas);
//                    System.out.println("天然气表数据存入TD是否成功：" + b);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
//            log.info("天然气表数据存入TD失败");
        }
    }

    /**
     * 工业看板类型
     *
     * @param id
     */
    public void storting(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    stortingMethodOptimize(id);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    public void stortingMethod(String id) {
        try {
            Equipment equipment = equipmentMapper.selectById(id);
            Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
            if (entries.size() > 0) {
                //根据deviceId查询楼层id
                String idAndType = getObjId(equipment);
                //根据设备id查询tags
                EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
                if (configuration != null && configuration.getTags() != null) {
                    Sorting sorting = new Sorting();
                    sorting.setEquipment_id(equipment.getId());
                    sorting.setTs(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    sorting.setObjId(idAndType);
                    sorting.setDeviceId(equipment.getDeviceId());
                    String s1 = IdUtil.simpleUUID();
                    sorting.setUid(s1);
                    sorting.setId(s1);
                    List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(configuration.getTags(), EquipmentDTO.AddressData.class);
                    for (EquipmentDTO.AddressData addressData : addressDataList) {
                        //尘埃粒子5.0
                        if (("longParticle").equals(addressData.getAttributeName()) && (entries.get(addressData.getAttributeName()) != null)) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            sorting.setLongParticle(parseFloat);
                        }
                        //尘埃粒子0.5
                        if ((("littleParticle").equals(addressData.getAttributeName())) && (entries.get(addressData.getAttributeName()) != null)) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            sorting.setLittleParticle(parseFloat);
                        }
                        //露点
                        if ((("dewPoint").equals(addressData.getAttributeName())) && (entries.get(addressData.getAttributeName()) != null)) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            sorting.setDewPoint(parseFloat);
                        }
                        //温度
                        if ((("temperature").equals(addressData.getAttributeName())) && (entries.get(addressData.getAttributeName()) != null)) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            sorting.setTemperature(parseFloat);
                        }
                        //湿度
                        if ((("humidity").equals(addressData.getAttributeName())) && (entries.get(addressData.getAttributeName()) != null)) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            sorting.setHumidity(parseFloat);
                        }
                        //静压
                        if ((("staticPressure").equals(addressData.getAttributeName())) && ((entries.get(addressData.getAttributeName()) != null))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            sorting.setStaticPressure(parseFloat);
                        }
                    }
                    boolean b = sortingMapper.addSorting(sorting);
//                    System.err.println("" + equipment.getDeviceId() + "数据存入TD是否成功:" + b);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
//            log.info("工业看板数据存入TD失败");
        }
    }

    /**
     * 工业看板优化
     *
     * @param id
     */
    public void stortingMethodOptimize(String id) throws Exception {
        try {
            Equipment equipment = equipmentMapper.selectById(id);
            Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
            List<EquipmentDTO.AddressData> addressDataList = null;
            //根据设备id查询tags
            EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
            if (configuration != null && configuration.getTags() != null && !"".equals(configuration.getTags())) {
                addressDataList = JSONArray.parseArray(configuration.getTags(), EquipmentDTO.AddressData.class);
            }
            //根据deviceId查询楼层id
            String idAndType = getObjId(equipment);

            if (entries.size() > 0 && "正常".equals(entries.get("type"))) {
                Sorting sorting = new Sorting();
                sorting.setEquipment_id(equipment.getId());
                sorting.setTs(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                sorting.setObjId(idAndType);
                sorting.setDeviceId(equipment.getDeviceId());
                String s1 = IdUtil.simpleUUID();
                sorting.setUid(s1);
                sorting.setId(s1);
                Class<? extends Sorting> sortingClass = sorting.getClass();
                //获取这个对象的所有属性
                Field[] fields = sortingClass.getDeclaredFields();
                if (fields.length > 0) {
                    //循环遍历所有属性，并赋值
                    for (Field field : fields) {
                        //获取属性名
                        String name = field.getName();
                        if (entries.containsKey(name)) {
                            Field declaredField = sortingClass.getDeclaredField(name);
                            declaredField.setAccessible(true);
                            float parseFloat = Float.parseFloat(entries.get(name).toString());
                            if (addressDataList != null) {
                                EquipmentDTO.AddressData data = addressDataList.stream().filter(addressData -> addressData.getAttributeName().equals(name)).findAny().orElse(null);
                                //这个属性是否做补偿值计算
                                if (data != null && data.getDeviation() != null && !"".equals(data.getDeviation())) {
                                    float deviation = Float.parseFloat(data.getDeviation());
                                    BigDecimal deviationDecimal = new BigDecimal(deviation);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                                }
                            }
                            declaredField.set(sorting, parseFloat);

                        }
                    }
                }
                boolean b = sortingMapper.addSorting(sorting);
                System.out.println("b = " + b);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }


    /**
     * 除湿机类型
     */
    public void dehumidifier(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                dehumidifierMethod(id);
            }
        });
    }

    public void dehumidifierMethod(String id) {
        try {
            Equipment equipment = equipmentMapper.selectById(id);
            if (equipment != null) {
                //根据设备的deviceId，查看Redis中是否推上来数据。有数据在存入TD
                Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
                if (entries.size() > 0) {
                    //根据deviceId查询楼层id
                    String idAndType = getObjId(equipment);

                    //根据设备id查询tags
                    EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
                    if (configuration != null && configuration.getTags() != null && !"".equals(configuration.getTags())) {
                        Dehumidifier dehumidifier = new Dehumidifier();
                        dehumidifier.setId(IdUtil.simpleUUID());
                        dehumidifier.setTs(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        dehumidifier.setDeviceId(equipment.getDeviceId());
                        dehumidifier.setEquipment_id(equipment.getId());
                        dehumidifier.setObjId(idAndType);
                        List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(configuration.getTags(), EquipmentDTO.AddressData.class);
                        for (EquipmentDTO.AddressData addressData : addressDataList) {
                            //回风露点
                            if (addressData.getAttributeName() != null && (addressData.getAttributeName().equals("returnAirDewPoint")) && (entries.get(addressData.getAttributeName()) != null)) {
                                float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                                //计算偏差后的值
                                if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                    float deviation = Float.parseFloat(addressData.getDeviation());
                                    BigDecimal deviationDecimal = new BigDecimal(deviation);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                                }
                                dehumidifier.setReturnAirDewPoint(parseFloat);
                            }
                            //回风温度
                            if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("returnAirTemperature").equals(addressData.getAttributeName()))) {
                                float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                                //计算偏差后的值
                                if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                    float deviation = Float.parseFloat(addressData.getDeviation());
                                    BigDecimal deviationDecimal = new BigDecimal(deviation);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                                }
                                dehumidifier.setReturnAirTemperature(parseFloat);
                            }
                            //  送风露点
                            if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("supplyAirDewPoint").equals(addressData.getAttributeName()))) {
                                float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                                //计算偏差后的值
                                if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                    float deviation = Float.parseFloat(addressData.getDeviation());
                                    BigDecimal deviationDecimal = new BigDecimal(deviation);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                                }
                                dehumidifier.setSupplyAirDewPoint(parseFloat);
                            }
                            //  送风温度
                            if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("supplyAirTemperature").equals(addressData.getAttributeName()))) {
                                float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                                //计算偏差后的值
                                if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                    float deviation = Float.parseFloat(addressData.getDeviation());
                                    BigDecimal deviationDecimal = new BigDecimal(deviation);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                                }
                                dehumidifier.setSupplyAirTemperature(parseFloat);
                            }
                            //  房间露点
                            if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("roomDewPoint").equals(addressData.getAttributeName()))) {
                                float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                                //计算偏差后的值
                                if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                    float deviation = Float.parseFloat(addressData.getDeviation());
                                    BigDecimal deviationDecimal = new BigDecimal(deviation);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                                }
                                dehumidifier.setRoomDewPoint(parseFloat);
                            }
                            //  房间温度
                            if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("roomTemperature").equals(addressData.getAttributeName()))) {
                                float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                                //计算偏差后的值
                                if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                    float deviation = Float.parseFloat(addressData.getDeviation());
                                    BigDecimal deviationDecimal = new BigDecimal(deviation);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                                }
                                dehumidifier.setRoomTemperature(parseFloat);
                            }

                        }
                        //存入TD
                        boolean b = dehumidifierMapper.addDehumidifier(dehumidifier);
                        System.out.println("b = " + b);
                    }
                }
            }
        } catch (NumberFormatException e) {
            throw new MyRException(ErrorEnums.NO_DATA);
        }
    }

    /**
     * 蒸汽
     *
     * @param id
     */
    public void getSteam(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                steamMethod(id);
            }
        });
    }

    public void steamMethod(@RequestParam String id) {
        try {
            Equipment equipment = equipmentMapper.selectById(id);
            Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
            if (entries.size() > 0) {
                //根据deviceId查询楼层id
                String idAndType = getObjId(equipment);
                //根据设备id查询tags
                EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
                if (configuration != null && configuration.getTags() != null) {
                    Steam steam = new Steam();
                    steam.setEquipment_id(equipment.getId());
                    steam.setId(IdUtil.simpleUUID());
                    steam.setTs(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    steam.setObjId(idAndType);
                    steam.setDeviceId(equipment.getDeviceId());
                    List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(configuration.getTags(), EquipmentDTO.AddressData.class);
                    for (EquipmentDTO.AddressData addressData : addressDataList) {
                        //瞬时计量
                        if (addressData.getAttributeName() != null && (addressData.getAttributeName().equals("instantaneous")) && (entries.get(addressData.getAttributeName()) != null)) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            steam.setInstantaneous(parseFloat);
                            //是否做差值计算
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    steam.setDet_instantaneous(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    steam.setDet_instantaneous(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }
                        //总量
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("total").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            steam.setTotal(parseFloat);
                            //是否做差值计算
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    steam.setDet_instantaneous(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    steam.setDet_instantaneous(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }
                        //  蒸汽温度
                        if (addressData.getAttributeName() != null && (entries.get(addressData.getAttributeName()) != null) && (("temperature").equals(addressData.getAttributeName()))) {
                            float parseFloat = Float.parseFloat(entries.get(addressData.getAttributeName()).toString());
                            //计算偏差后的值
                            if (addressData.getDeviation() != null && !"".equals(addressData.getDeviation())) {
                                float deviation = Float.parseFloat(addressData.getDeviation());
                                BigDecimal deviationDecimal = new BigDecimal(deviation);
                                BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                parseFloat = nowBigDecimal.add(deviationDecimal).floatValue();
                            }
                            steam.setTotal(parseFloat);
                            //是否做差值计算
                            if (((addressData.getIsDifference() != null) && (addressData.getIsDifference().equals("1"))) || ((addressData.getPostProcessing() != null) && (addressData.getPostProcessing().equals("差值计算")))) {
                                //这个属性做差值计算,从hashmap去上次存的值  key:dataId
                                if (hashMap.get(addressData.getDataId()) != null) {
                                    Float lastFloat = hashMap.get(addressData.getDataId());
                                    BigDecimal lastBigDecimal = new BigDecimal(lastFloat);
                                    BigDecimal nowBigDecimal = new BigDecimal(parseFloat);
                                    float v = nowBigDecimal.subtract(lastBigDecimal).floatValue();
                                    steam.setDet_instantaneous(v);
                                    //把当前读取到的值存进去
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                } else {
                                    steam.setDet_instantaneous(0);
                                    hashMap.put(addressData.getDataId(), parseFloat);
                                }
                            } else if ((addressData.getIsDifference() == null || addressData.getPostProcessing() == null || addressData.getIsDifference().equals("0") || (!(addressData.getPostProcessing().equals("差值计算")))) && hashMap.get(addressData.getDataId()) != null) {
                                //不做差值，就把以前存的东西删掉
                                hashMap.remove(addressData.getDataId());
                            }
                        }
                    }
                    boolean b = steamMapper.addSteam(steam);
//                    System.out.println("蒸汽数据存入TD是否成功：" + b);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
//            log.info("蒸汽数据存入TD失败");
        }
    }

    private String getObjId(Equipment equipment) {
        List<String> objId = objMiddleMapper.findByDeviceId(equipment.getDeviceId());
        if (objId != null) {
            for (String s : objId) {
                String type = objMoudelMapper.findIdAndType(s, "1");
                if (type != null) {
                    return type;
                }
            }
        }
        return "";
    }

    /**
     * 每过十分钟，判断一下设备有没有修改
     */
    public void updateQuartz(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    updateQuartzMethod(id);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    public void updateQuartzMethod(String param) throws Exception {
        try {
            //当前时间
            DateTime nowTime = new DateTime();
            //前十分钟的时间
            DateTime tenTimeAgo = nowTime.offsetNew(DateField.MINUTE, -10);
            List<Equipment> equipmentList = equipmentMapper.findByTenTimeAgo(nowTime, tenTimeAgo);
            if (equipmentList.size() > 0) {
                for (Equipment equipment : equipmentList) {
                    String S = QuartzUtils.type(equipment.getId(), equipment.getType());
                    QuartzJob job = quartzMapper.selectByInvokeTarget(S);
                    if (job != null) {
                        //数据库中已经存在这个设备的定时任务，就更新定时任务
                        String type = QuartzUtils.type(equipment.getId(), equipment.getType());  //根据设备类型调用指定的方法
                        job.setInvokeTarget(type);
                        String cycle = QuartzUtils.cycle(equipment.getCycle()); //定时任务执行周期
                        job.setCronExpression(cycle);
                        job.setJobName(equipment.getDeviceId());
                        int updateJob = iQuartzJobService.updateJob(job);
                        if (updateJob > 0) {
                            log.info(equipment.getDeviceId() + "更新定时任务成功");
                        } else {
                            log.info(equipment.getDeviceId() + "更新定时任务失败");
                        }
                    } else {
                        //数据库中还未存在这个定时任务，就新增
                        QuartzJob quartzJob = new QuartzJob();
                        String corn = QuartzUtils.cycle(equipment.getCycle());
                        quartzJob.setCronExpression(corn);
                        quartzJob.setJobName(equipment.getDeviceId());
                        quartzJob.setJobGroup("DEFAULT");
                        String invokeTarget = QuartzUtils.type(equipment.getId(), equipment.getType());
                        quartzJob.setInvokeTarget(invokeTarget);
                        quartzJob.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
                        quartzJob.setConcurrent("1");
                        quartzJob.setStatus("0");
                        quartzJob.setRemark("系统自动创建" + equipment.getDeviceId() + "的任务");
                        int insert = iQuartzJobService.insertJob(quartzJob);
                        if (insert > 0) {
                            log.info(equipment.getDeviceId() + "新增定时任务成功");
                        } else {
                            log.info(equipment.getDeviceId() + "新增定时任务失败");
                        }
                    }

                }
            } else {
//                System.out.println("暂无定时任务需要修改");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void defaultMethods(String id) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    defaultMethod(id);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    /**
     * TODO 别的设备类型不知道要不要采集数据，就先留着
     *
     * @param param
     */
    public void defaultMethod(String param) throws Exception {


    }

    public void PLCCollect(String id) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(sra, true);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    PLCCollectMethod(id);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    // plc采集方式
    public void PLCCollectMethod(String param) throws Exception {

        Equipment equipment = equipmentMapper.selectById(param);
        if (equipment != null) {
            EquipmentConfiguration equipmentConfiguration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
            if (equipmentConfiguration != null && equipmentConfiguration.getTags() != null && !"".equals(equipmentConfiguration.getTags())) {
                List<EquipmentDTO.AddressData> addressDataList = JSONArray.parseArray(equipmentConfiguration.getTags(), EquipmentDTO.AddressData.class);
                addressDataList.stream().forEach(addressData -> {
                    //根据设备id去Redis查找数据
                    Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
                    if (entries.size() > 0) {
                        //Redis中存入的上下限是否报警 longParticleup longParticledown longParticleIsAlarm
                        String up = addressData.getAttributeName() + "up";
                        String down = addressData.getAttributeName() + "down";
                        String IsAlarm = addressData.getAttributeName() + "IsAlarm";
                        String deviation = addressData.getAttributeName() + "deviation";
                        //plc采集的上限 有就保存进tags中
                        if (entries.containsKey(up)) {
                            String stringUp = (entries.get(up).toString());
                            addressData.setUp(stringUp);
                        }
                        //plc采集的下限，有就保存进tags中
                        if (entries.containsKey(down)) {
                            String stringDown = (entries.get(down).toString());
                            addressData.setDown(stringDown);
                        }
                        //plc采集的补偿值，有就保存进tags中
                        if (entries.containsKey(deviation)) {
                            String stringDown = (entries.get(deviation).toString());
                            addressData.setDeviation(stringDown);
                        }
                        //plc采集的是否报警，有就保存进tags中
                        if (entries.containsKey(IsAlarm)) {
                            addressData.setIsAlarm(Boolean.parseBoolean((entries.get(IsAlarm).toString())) ? "1" : "0");
                        }
                    }
                });
                System.out.println("equipmentConfiguration.getTags() = " + addressDataList);
                equipmentConfiguration.setTags(JSON.toJSONString(addressDataList));
                //把保存的tags存入数据库 thread-bound
                equipmentConfigMapper.updateById(equipmentConfiguration);
            }
        }
    }

}
